<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blogs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="正则表达式,">










<meta name="keywords" content="正则表达式">
<meta property="og:type" content="article">
<meta property="og:title" content="图学正则表达式">
<meta property="og:url" content="https://wangzichong.gitee.io/blogs/2019/07/14/t-正则表达式/regExp/index.html">
<meta property="og:site_name" content="Reading Notes">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1mYtNakL0gK0jSZFt760QCXXac.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1HtdxaXT7gK0jSZFp761TkpXam.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB16V8DakL0gK0jSZFx760WHVXax.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1PhVBaeT2gK0jSZFv760nFXXa3.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1ZD4Caa61gK0jSZFl760DKFXax.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1q0G3XubviK0jSZFN761ApXXaR.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1ctXCafb2gK0jSZK9761EgFXaA.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1QV8Eahv1gK0jSZFF7620sXXa1.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1Qp0HabY1gK0jSZTE760DQVXao.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1uPdGaoH1gK0jSZSy760tlpXaZ.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1.4xIabH1gK0jSZFw7637aXXaB.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1G1lJamf2gK0jSZFP760sopXau.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1C94MaeH2gK0jSZFE763qMpXab.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1iUNSabH1gK0jSZFw7637aXXar.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1LU0Raoz1gK0jSZLe7629kVXar.png">
<meta property="og:image" content="https://ae01.alicdn.com/kf/HTB1S9h4abH1gK0jSZFw7637aXXaK.png">
<meta property="og:updated_time" content="2019-07-20T15:40:47.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="图学正则表达式">
<meta name="twitter:image" content="https://ae01.alicdn.com/kf/HTB1mYtNakL0gK0jSZFt760QCXXac.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blogs/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangzichong.gitee.io/blogs/2019/07/14/t-正则表达式/regExp/">





  <title>图学正则表达式 | Reading Notes</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Reading Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Codes Change Life</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blogs/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blogs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangzichong.gitee.io/blogs/blogs/2019/07/14/t-正则表达式/regExp/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zichong">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blogs/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Reading Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">图学正则表达式</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-14T13:07:51+08:00">
                2019-07-14
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogs/categories/学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          
              <div class="post-description">
                   
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <a id="more"></a>
<h3 id="图形工具的应用"><a href="#图形工具的应用" class="headerlink" title="图形工具的应用"></a>图形工具的应用</h3><h4 id="工具介绍"><a href="#工具介绍" class="headerlink" title="工具介绍"></a>工具介绍</h4><ul>
<li>图形工具: <a href="https://regexper.com/" target="_blank">regexper</a></li>
<li>在线测试工具: <a href="https://regexr.com/" target="_blank">regexr</a></li>
</ul>
<h4 id="部分图解案例"><a href="#部分图解案例" class="headerlink" title="部分图解案例"></a>部分图解案例</h4><table>
<thead>
<tr>
<th>正则</th>
<th>释义</th>
<th>图解</th>
</tr>
</thead>
<tbody><tr>
<td>\d</td>
<td>一个数字</td>
<td><img src="https://ae01.alicdn.com/kf/HTB1mYtNakL0gK0jSZFt760QCXXac.png" alt="\d"></td>
</tr>
<tr>
<td>\d?</td>
<td>零个或者一个数字</td>
<td><img src="https://ae01.alicdn.com/kf/HTB1HtdxaXT7gK0jSZFp761TkpXam.png" alt="\d?"></td>
</tr>
<tr>
<td>\d+</td>
<td>一个或者多个数字</td>
<td><img src="https://ae01.alicdn.com/kf/HTB16V8DakL0gK0jSZFx760WHVXax.png" alt="\d+"></td>
</tr>
<tr>
<td>\d{3,5}</td>
<td>三个或者五个数字</td>
<td><img src="https://ae01.alicdn.com/kf/HTB1PhVBaeT2gK0jSZFv760nFXXa3.png" alt="\d{3,5}"></td>
</tr>
<tr>
<td>\d*</td>
<td>零个, 一个, 多个, 任意个数字</td>
<td><img src="https://ae01.alicdn.com/kf/HTB1ZD4Caa61gK0jSZFl760DKFXax.png" alt="\d*"></td>
</tr>
<tr>
<td>\bis\b</td>
<td>is的单词边界</td>
<td><img src="https://ae01.alicdn.com/kf/HTB1q0G3XubviK0jSZFN761ApXXaR.png" alt="\bis\b"></td>
</tr>
</tbody></table>
<h4 id="小试牛刀"><a href="#小试牛刀" class="headerlink" title="小试牛刀"></a>小试牛刀</h4><ul>
<li>去掉https协议的png文件的协议头(用分组 -&gt; $1表示第一个分组)<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/https:(\/\/.+\.png)/</span>;</span><br><span class="line"><span class="keyword">var</span> imgUrl = <span class="string">'https://ae01.alicdn.com/kf/HTB1HtdxaXT7gK0jSZFp761TkpXam.png'</span>;</span><br><span class="line">imgUrl.replace(reg, <span class="string">'$1'</span>);</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p><img src="https://ae01.alicdn.com/kf/HTB1ctXCafb2gK0jSZK9761EgFXaA.png" alt="replace"> </p>
<ul>
<li>日期替换(分组, $1$2$3)<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/(^\d&#123;4&#125;)[/-](\d&#123;2&#125;)[/-](\d&#123;2&#125;)$/</span>;</span><br><span class="line"><span class="string">'2016/02/12'</span>.replace(reg, <span class="string">'$2-$3-$1'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// replace可以接收回调函数, a表示匹配到的正则, bcd表示匹配的分组内容</span></span><br><span class="line"><span class="string">'2016/02/12'</span>.replace(reg, <span class="function"><span class="keyword">function</span>(<span class="params">a, b, c, d</span>)</span>&#123; <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;c&#125;</span>-<span class="subst">$&#123;d&#125;</span>-<span class="subst">$&#123;b&#125;</span>`</span> &#125;);</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p><img src="https://ae01.alicdn.com/kf/HTB1QV8Eahv1gK0jSZFF7620sXXa1.png" alt="replace"></p>
<h3 id="RegExp对象"><a href="#RegExp对象" class="headerlink" title="RegExp对象"></a>RegExp对象</h3><h4 id="修饰符"><a href="#修饰符" class="headerlink" title="修饰符"></a>修饰符</h4><ul>
<li>g: global全文搜索, 如果不添加, 搜索到第一个匹配, 即停止</li>
<li>i: ignore case忽略大小写, 默认大小写敏感</li>
<li>m: multiple lines多行搜索<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// i的使用</span></span><br><span class="line"><span class="string">'She is a girl. Is she?'</span>.replace(<span class="regexp">/\bis\b/g</span>, <span class="string">'1'</span>);</span><br><span class="line">  <span class="comment">// "She 1 a girl. Is she?" 只匹配了第一个is, 加上i即可 忽略大小写</span></span><br><span class="line"><span class="string">'She is a girl. Is she?'</span>.replace(<span class="regexp">/\bis\b/gi</span>, <span class="string">'1'</span>);</span><br><span class="line">  <span class="comment">// "She 1 a girl. 1 she?"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// g的使用</span></span><br><span class="line"><span class="string">'She is a girl. Is she?'</span>.replace(<span class="regexp">/\bis\b/i</span>, <span class="string">'1'</span>);</span><br><span class="line">  <span class="comment">// "She 1 a girl. Is she?" 只匹配了第一个</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h4 id="元字符"><a href="#元字符" class="headerlink" title="元字符"></a>元字符</h4><p>正则是由两种基本字符类型组成, 分别是 <strong>原义文本字符</strong> 和 <strong>元字符</strong></p>
<ul>
<li>原义文本字符: 正常的字符, 如a, b, c, d</li>
<li>元字符: 有特殊含义的非字母字符, 如* + ? $ ^ . | \ () {} []</li>
</ul>
<h4 id="字符类"><a href="#字符类" class="headerlink" title="字符类"></a>字符类</h4><ul>
<li><p>一般情况下正则表达式一个字符对应字符串的一个字符</p>
<ul>
<li>abc\n : 表示abc字符加一个tab制表符(与正则表达式一一对应)<br><img src="https://ae01.alicdn.com/kf/HTB1Qp0HabY1gK0jSZTE760DQVXao.png" alt="reg-8"></li>
</ul>
</li>
<li><p>使用[]来构建一个简单的类(符合某些特性的对象), 如[abc]把字符a或b或c归为一类, 可以匹配这类字符<br><img src="https://ae01.alicdn.com/kf/HTB1uPdGaoH1gK0jSZSy760tlpXaZ.png" alt="reg-9"></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'a1b2c3d4a2a1'</span>.replace(<span class="regexp">/[abcd]/g</span>, <span class="string">'Y'</span>);</span><br><span class="line"><span class="comment">// "Y1Y2Y3Y4Y2Y1"</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>字符类取反</p>
<ul>
<li>使用元字符 ^ 来创建反向类(不属于某类的内容)</li>
<li>[^abc]表示不是字符a或b或c的内容<br><img src="https://ae01.alicdn.com/kf/HTB1.4xIabH1gK0jSZFw7637aXXaB.png" alt="reg-10"><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'a1b2c3a2a1'</span>.replace(<span class="regexp">/[^abc]/g</span>, <span class="string">'Y'</span>);</span><br><span class="line"><span class="comment">// "aYbYcYaYaY"</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
</li>
</ul>
<h4 id="范围类"><a href="#范围类" class="headerlink" title="范围类"></a>范围类</h4><p>使用[a-z]来连接两个字符, 表示从a到z的任意字符(包含两个字符本身), 也可以[a-zA-Z0-9]</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'a1b2c3d4x5y6z7'</span>.replace(<span class="regexp">/[a-z]/g</span>, <span class="string">'M'</span>);</span><br><span class="line"><span class="comment">// "M1M2M3M4M5M6M7"</span></span><br></pre></td></tr></table></figure>

<h4 id="预定义类"><a href="#预定义类" class="headerlink" title="预定义类"></a>预定义类</h4><table>
<thead>
<tr>
<th>字符</th>
<th>等价类</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>.</td>
<td>[^\r\n]</td>
<td>除了回车和换行符之外的所有字符</td>
</tr>
<tr>
<td>\d</td>
<td>[0-9]</td>
<td>数字字符</td>
</tr>
<tr>
<td>\D</td>
<td>[^0-9]</td>
<td>非数字字符</td>
</tr>
<tr>
<td>\s</td>
<td>[\t\n\x0B\f\r]</td>
<td>空白符</td>
</tr>
<tr>
<td>\S</td>
<td>[^\t\n\x0B\f\r]</td>
<td>非空白符</td>
</tr>
<tr>
<td>\w</td>
<td>[a-zA-Z_0-9]</td>
<td>单词字符(字母, 数字, 下划线)</td>
</tr>
<tr>
<td>\W</td>
<td>[^a-zA-Z_0-9]</td>
<td>非单词字符</td>
</tr>
</tbody></table>
<ul>
<li>匹配一个 ab + 数字 + 任意字符 的字符串<ul>
<li>ab\d.<br><img src="https://ae01.alicdn.com/kf/HTB1G1lJamf2gK0jSZFP760sopXau.png" alt="reg-11"></li>
</ul>
</li>
</ul>
<h4 id="边界"><a href="#边界" class="headerlink" title="边界"></a>边界</h4><table>
<thead>
<tr>
<th>字符</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>^</td>
<td>以xxx为开始</td>
</tr>
<tr>
<td>$</td>
<td>以xxx为结尾</td>
</tr>
<tr>
<td>\b</td>
<td>单词边界</td>
</tr>
<tr>
<td>\B</td>
<td>非单词边界</td>
</tr>
</tbody></table>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 替换所有带'is'</span></span><br><span class="line"><span class="string">'This is a girl'</span>.replace(<span class="regexp">/is/g</span>, <span class="string">'0'</span>)</span><br><span class="line">  <span class="comment">// "Th0 0 a girl"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 替换单词 'is'</span></span><br><span class="line"><span class="string">'This is a girl'</span>.replace(<span class="regexp">/\bis\b/g</span>, <span class="string">'0'</span>)</span><br><span class="line">  <span class="comment">// "This 0 a girl"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 替换单词 'This'中的'is'</span></span><br><span class="line"><span class="string">'This is a girl'</span>.replace(<span class="regexp">/\Bis\b/g</span>, <span class="string">'0'</span>)</span><br><span class="line">  <span class="comment">// "Th0 is a girl"</span></span><br></pre></td></tr></table></figure>

<h4 id="量词"><a href="#量词" class="headerlink" title="量词"></a>量词</h4><p>用来指明某个字符串匹配的次数(作用于紧挨着的字符)</p>
<table>
<thead>
<tr>
<th>字符</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>?</td>
<td>出现零次或者一次(最多出现一次)</td>
</tr>
<tr>
<td>+</td>
<td>出现一次或者多次(至少出现一次)</td>
</tr>
<tr>
<td>*</td>
<td>出现零次或者多次(任意次)</td>
</tr>
<tr>
<td>{n}</td>
<td>出现n次</td>
</tr>
<tr>
<td>{n,m}</td>
<td>出现n到m次</td>
</tr>
<tr>
<td>{n,}</td>
<td>至少出现n次</td>
</tr>
</tbody></table>
<ul>
<li>希望匹配一个连续出现5次的数字字符串<ul>
<li>\d\d\d\d\d -&gt; \d{5}</li>
</ul>
</li>
<li>复杂例子<ul>
<li>\d{20}\w\d?\w+\d*\d{3}\w{3,5}\d{3,}<br><img src="https://ae01.alicdn.com/kf/HTB1C94MaeH2gK0jSZFE763qMpXab.png" alt="reg-12"></li>
</ul>
</li>
</ul>
<h4 id="贪婪模式与非贪婪模式"><a href="#贪婪模式与非贪婪模式" class="headerlink" title="贪婪模式与非贪婪模式"></a>贪婪模式与非贪婪模式</h4><p>贪婪模式: 正则在默认的情况是尽可能多地去匹配<br>非贪婪模式: 让正则尽量少的匹配, 一旦匹配成功, 就不再继续(在量词后面加上 <strong>?</strong> 即可)</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 贪婪匹配</span></span><br><span class="line"><span class="string">'12345678'</span>.replace(<span class="regexp">/\d&#123;3,6&#125;/g</span>, <span class="string">'X'</span>);</span><br><span class="line">  <span class="comment">// "X78"</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 非贪婪匹配</span></span><br><span class="line"><span class="string">'12345678'</span>.replace(<span class="regexp">/\d&#123;3,6&#125;?/g</span>, <span class="string">'X'</span>);</span><br><span class="line">  <span class="comment">// "XX78"</span></span><br></pre></td></tr></table></figure>

<h4 id="分组"><a href="#分组" class="headerlink" title="分组"></a>分组</h4><p>使用小括号来指定子表达式</p>
<ul>
<li>匹配字符串test连续出现3次, test{3}表示t出现3次<ul>
<li>用()可以达到分组的功能, 使量词作用于分组, 即 (test){3}</li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 匹配小写英语字母加一个数字连续出现3次</span></span><br><span class="line"><span class="string">'a1b2c3d4'</span>.replace(<span class="regexp">/([a-z]\d)&#123;3&#125;/</span>, <span class="string">'X'</span>);</span><br><span class="line">  <span class="comment">// "Xd4"</span></span><br></pre></td></tr></table></figure>

<h4 id="或"><a href="#或" class="headerlink" title="或"></a>或</h4><p>使用 | 来表示或</p>
<ul>
<li>abc|def<br><img src="https://ae01.alicdn.com/kf/HTB1iUNSabH1gK0jSZFw7637aXXar.png" alt="reg-13"></li>
<li>ab(c|d)ef<br><img src="https://ae01.alicdn.com/kf/HTB1LU0Raoz1gK0jSZLe7629kVXar.png" alt="reg-14"></li>
</ul>
<h4 id="反向引用"><a href="#反向引用" class="headerlink" title="反向引用"></a>反向引用</h4><p>使用分组指定一个子表达式后, 匹配这个子表达式的文本(也就是此分组捕获的内容)可以在表达式或其它程序中作进一步的处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 2019-12-25 替换成 12/25/2019</span></span><br><span class="line"><span class="comment">// $ 表示分组内的内容</span></span><br><span class="line"><span class="string">'2019-12-25'</span>.replace(<span class="regexp">/(\d&#123;4&#125;)-(\d&#123;2&#125;)-(\d&#123;2&#125;)/g</span>, <span class="string">'$2/$3/$1'</span>);</span><br><span class="line">  <span class="comment">// "12/25/2019"</span></span><br></pre></td></tr></table></figure>

<p>忽略分组(匹配不捕获分组), 只要在分组内加上 <strong>?:</strong> 即可</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 匹配捕获</span></span><br><span class="line"><span class="string">'testabc'</span>.replace(<span class="regexp">/(abc)/g</span>, <span class="string">'[$1]'</span>);</span><br><span class="line">  <span class="comment">// "test[abc]"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 匹配不捕获</span></span><br><span class="line"><span class="string">'testabc'</span>.replace(<span class="regexp">/(?:abc)/g</span>, <span class="string">'[$1]'</span>)</span><br><span class="line">  <span class="comment">// "test[$1]"</span></span><br></pre></td></tr></table></figure>

<h4 id="前瞻"><a href="#前瞻" class="headerlink" title="前瞻"></a>前瞻</h4><p>正则表达式从文本头部向尾部解析, 文本尾部方向称为 ‘前’</p>
<ul>
<li>前瞻: 就是在正则表达式匹配到规则的时候, 向前检查是否符合断言(<strong>断言部分不参与操作, 比如替换</strong>), 后顾则与之相反(js不支持后顾)<ul>
<li>正向前瞻 exp(?=assert)<ul>
<li>匹配后面满足表达式exp的位置</li>
</ul>
</li>
<li>负向前瞻 exp(?!assert)<ul>
<li>匹配后面不满足表达式exp的位置</li>
</ul>
</li>
</ul>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">// 匹配到单词字符后, 向前看下, 单词字符后面的是不是一个数字</span><br><span class="line">&apos;abc&apos;.replace(/\w(?=\d)/g, &apos;X&apos;);</span><br><span class="line">  // &quot;abc&quot;</span><br><span class="line">&apos;abc2&apos;.replace(/\w(?=\d)/g, &apos;X&apos;);</span><br><span class="line">  // &quot;abX2&quot;</span><br><span class="line"></span><br><span class="line">// 匹配到单词字符后, 向前看下, 单词字符后面 不是一个数字</span><br><span class="line">&apos;abc2&apos;.replace(/\w(?!\d)/g, &apos;X&apos;);</span><br><span class="line">  // &quot;XXcX&quot;</span><br></pre></td></tr></table></figure>

<h3 id="对象属性"><a href="#对象属性" class="headerlink" title="对象属性"></a>对象属性</h3><ul>
<li>global: 是否全文搜索, 默认false</li>
<li>ignore case: 是否大小写敏感, 默认false</li>
<li>multiline: 多行搜索, 默认false</li>
<li>lastIndex: 当前匹配结果的最后一个字符的下一个字符</li>
<li>source: 正则表达式的文本字符串</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/\d/</span>;</span><br><span class="line"><span class="built_in">console</span>.log(reg.global); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(reg.multiline); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(reg.ignoreCase); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(reg.source); <span class="comment">// '\d'</span></span><br><span class="line"><span class="built_in">console</span>.log(reg.lastIndex); <span class="comment">// 0</span></span><br></pre></td></tr></table></figure>

<h3 id="对象的方法-text-和-exec"><a href="#对象的方法-text-和-exec" class="headerlink" title="对象的方法(text 和 exec)"></a>对象的方法(text 和 exec)</h3><h4 id="test"><a href="#test" class="headerlink" title="test"></a>test</h4><p>用于测试字符串参数中是否存在匹配正则表达式模式的字符串, 返回true 或 false</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">/\w/g.test(<span class="string">'ab'</span>);</span><br><span class="line"><span class="comment">// lastIndex: 当前匹配结果的最后一个字符的下一个字符</span></span><br><span class="line">  <span class="comment">// 1.当前匹配字符 2.最后一个字符 3.下一个字符</span></span><br><span class="line">  <span class="comment">// 第一次执行后, 匹配的结果是a, 它的最后一个字符还是a, 它的下一个字符为b, 则 lastIndex 为1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/\w/g</span>;</span><br><span class="line"><span class="keyword">while</span>(reg.test(<span class="string">'ab'</span>)) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(reg.lastIndex); <span class="comment">// 1 和 2</span></span><br><span class="line">  <span class="comment">// 当执行第三次的时候, lastIndex为 2 了, test返回为 false了</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="exec"><a href="#exec" class="headerlink" title="exec"></a>exec</h4><p>使正则表达式模式对字符串执行搜索, 并将更新全局regexp对象的属性, 来反映匹配结果</p>
<ul>
<li>如果没有匹配的文本则返回null, 反之返回一个数组</li>
<li>数组详解<ul>
<li>index 被匹配字符串的第一个字符的位置</li>
<li>input 存放被检索的字符串</li>
<li>第一个元素是与正则表达式相匹配的文本</li>
<li>第二个元素是第一个分组(如果有的话)</li>
<li>第三个元素是第二个分组(如果有的话)</li>
</ul>
</li>
</ul>
<p>非全局调用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/\d(\w)\d/</span>;</span><br><span class="line"><span class="keyword">var</span> testStr = <span class="string">'$1a2b3c4d5e'</span>;</span><br><span class="line"><span class="keyword">var</span> ret = reg.exec(testStr);</span><br><span class="line"><span class="comment">// ret[0] -&gt; 与正则表达式相匹配的文本, 即 '1a2'</span></span><br><span class="line"><span class="comment">// ret[1] -&gt; 第一个分组, 即 'a'</span></span><br><span class="line"><span class="comment">// ret[2] -&gt; 不存在第二个分组, 则该值不存在</span></span><br><span class="line"><span class="comment">// ret.index -&gt; 被匹配字符串的第一个字符的位置, '1a2' 即 1</span></span><br><span class="line"><span class="comment">// ret.input -&gt; 存放被检索的字符串, 即 '$1a2b3c4d5e'</span></span><br><span class="line"><span class="comment">// 因为非全局调用, reg.lastIndex 始终为 0</span></span><br></pre></td></tr></table></figure>

<p>全局调用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/\d(\w)(\w)\d/g</span>;</span><br><span class="line"><span class="keyword">var</span> testStr = <span class="string">'$1av2bw3cx4dy5ez'</span>;</span><br><span class="line"><span class="keyword">var</span> ret;</span><br><span class="line"><span class="keyword">while</span>(ret = reg.exec(testStr)) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(ret);</span><br><span class="line">  <span class="built_in">console</span>.log(reg.lastIndex);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://ae01.alicdn.com/kf/HTB1S9h4abH1gK0jSZFw7637aXXaK.png" alt="reg-15"></p>
<h3 id="与正则表达式相关的字符串方法"><a href="#与正则表达式相关的字符串方法" class="headerlink" title="与正则表达式相关的字符串方法"></a>与正则表达式相关的字符串方法</h3><h4 id="search"><a href="#search" class="headerlink" title="search"></a>search</h4><p>用于检索字符串中指定的子字符串, 或检索与正则表达式相匹配的子字符串</p>
<ul>
<li>忽略g标志, 并且总是从字符串的开始进行检索</li>
<li>返回第一个匹配结果的index, 匹配不到返回 -1<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&apos;a1b2c1d1&apos;.search(&apos;1&apos;);</span><br><span class="line">&apos;a1b2c1d1&apos;.search(/1/g);</span><br><span class="line">// 1</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h4 id="match"><a href="#match" class="headerlink" title="match"></a>match</h4><p>用于检索字符串一个或者多个与正则匹配的文本</p>
<ul>
<li>如果没有g, 那么该方法只能在字符串中执行一次匹配<ul>
<li>如果没有找到匹配文本, 则返回null, 否则返回数组</li>
<li>返回的数组<ul>
<li>index 被匹配字符串的第一个字符的位置</li>
<li>input stringObject的引用</li>
<li>第一个元素存放的是匹配的字符串</li>
<li>第二个元素是第一个分组(如果有的话)</li>
<li>第三个元素是第二个分组(如果有的话)</li>
</ul>
</li>
</ul>
</li>
<li>如果有g, 那么该方法会进行全局搜索, 找到字符串中所有匹配的字符串<ul>
<li>如果没有找到匹配文本, 则返回null, 否则(找到一个或多个匹配串)返回数组</li>
<li>返回的数组<ul>
<li>存放所有的匹配文本</li>
<li>没有index 和 input属性</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>非全局调用(与exec返回结果一致)</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/\d(\w)\d/</span>;</span><br><span class="line"><span class="keyword">var</span> testStr = <span class="string">'$1a2b3c4d5e'</span>;</span><br><span class="line"><span class="keyword">var</span> ret = testStr.match(reg);</span><br><span class="line"><span class="comment">// ret[0] -&gt; 与正则表达式相匹配的文本, 即 '1a2'</span></span><br><span class="line"><span class="comment">// ret[1] -&gt; 第一个分组, 即 'a'</span></span><br><span class="line"><span class="comment">// ret[2] -&gt; 不存在第二个分组, 则该值不存在</span></span><br><span class="line"><span class="comment">// ret.index -&gt; 被匹配字符串的第一个字符的位置, '1a2' 即 1</span></span><br><span class="line"><span class="comment">// ret.input -&gt; stringObject的引用, 即 '$1a2b3c4d5e'</span></span><br><span class="line"><span class="comment">// reg.lastIndex 为 0</span></span><br></pre></td></tr></table></figure>

<p>全局调用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/\d(\w)\d/g</span>;</span><br><span class="line"><span class="keyword">var</span> testStr = <span class="string">'$1a2b3c4d5e'</span>;</span><br><span class="line"><span class="keyword">var</span> ret = testStr.match(reg);</span><br><span class="line"><span class="built_in">console</span>.log(ret); <span class="comment">// ["1a2", "3c4"]</span></span><br><span class="line"><span class="comment">// reg.lastIndex 为 0</span></span><br></pre></td></tr></table></figure>

<h4 id="split"><a href="#split" class="headerlink" title="split"></a>split</h4><p>用于把字符串分割成字符串数组</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'abcde'</span>.split(<span class="string">''</span>);</span><br><span class="line">  <span class="comment">// ["a", "b", "c", "d", "e"]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 复杂的分割, 可以用正则</span></span><br><span class="line"><span class="string">'a1b2c3d'</span>.split(<span class="regexp">/\d/</span>)</span><br><span class="line">  <span class="comment">// ["a", "b", "c", "d"]</span></span><br></pre></td></tr></table></figure>

<h4 id="replace"><a href="#replace" class="headerlink" title="replace"></a>replace</h4><p>用于在字符串中用一些字符替换另一些字符, 或替换一个与正则表达式匹配的子串</p>
<ul>
<li>第一个参数可以是 string / regexp</li>
<li>第二个参数可以是 替换的string / callback</li>
<li>当为callback时(每匹配一次都调用一次), 有四个参数(实际参数受分组影响)<ol>
<li>匹配的字符串</li>
<li>分组的内容, 如果没有分组就没有该参数, 如果有多个分组, 接下去的几个参数为对应的分组内容</li>
<li>匹配项在字符串中的index</li>
<li>原字符串<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> res = <span class="string">'a1b2c3d4e5'</span>.replace(<span class="regexp">/(\d)(\w)(\d)/g</span>, <span class="function"><span class="keyword">function</span>(<span class="params">match, group1, group2, group3, index, origin</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(match, group1, group2, group3, index, origin);</span><br><span class="line">  <span class="comment">// 1b2 1 b 2 1 a1b2c3d4e5</span></span><br><span class="line">  <span class="comment">// 3d4 3 d 4 5 a1b2c3d4e5</span></span><br><span class="line">  <span class="keyword">return</span> group1 + group3  <span class="comment">//  12  34</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(res); <span class="comment">// "a12c34e5"</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/正则表达式/" rel="tag"># 正则表达式</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2019/07/12/t-NodeJs/Comet-webSocket-SSE/" rel="next" title="数据推送技术之Comet, WebSocket, SSE">
                <i class="fa fa-chevron-left"></i> 数据推送技术之Comet, WebSocket, SSE
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2019/07/17/t-NodeJs/nodejs-info/" rel="prev" title="NodeJS那些事(一)">
                NodeJS那些事(一) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">zichong</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives/">
              
                  <span class="site-state-item-count">39</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blogs/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#图形工具的应用"><span class="nav-number">1.</span> <span class="nav-text">图形工具的应用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#工具介绍"><span class="nav-number">1.1.</span> <span class="nav-text">工具介绍</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#部分图解案例"><span class="nav-number">1.2.</span> <span class="nav-text">部分图解案例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#小试牛刀"><span class="nav-number">1.3.</span> <span class="nav-text">小试牛刀</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RegExp对象"><span class="nav-number">2.</span> <span class="nav-text">RegExp对象</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#修饰符"><span class="nav-number">2.1.</span> <span class="nav-text">修饰符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#元字符"><span class="nav-number">2.2.</span> <span class="nav-text">元字符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#字符类"><span class="nav-number">2.3.</span> <span class="nav-text">字符类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#范围类"><span class="nav-number">2.4.</span> <span class="nav-text">范围类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#预定义类"><span class="nav-number">2.5.</span> <span class="nav-text">预定义类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#边界"><span class="nav-number">2.6.</span> <span class="nav-text">边界</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#量词"><span class="nav-number">2.7.</span> <span class="nav-text">量词</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#贪婪模式与非贪婪模式"><span class="nav-number">2.8.</span> <span class="nav-text">贪婪模式与非贪婪模式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#分组"><span class="nav-number">2.9.</span> <span class="nav-text">分组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#或"><span class="nav-number">2.10.</span> <span class="nav-text">或</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#反向引用"><span class="nav-number">2.11.</span> <span class="nav-text">反向引用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#前瞻"><span class="nav-number">2.12.</span> <span class="nav-text">前瞻</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#对象属性"><span class="nav-number">3.</span> <span class="nav-text">对象属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#对象的方法-text-和-exec"><span class="nav-number">4.</span> <span class="nav-text">对象的方法(text 和 exec)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#test"><span class="nav-number">4.1.</span> <span class="nav-text">test</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#exec"><span class="nav-number">4.2.</span> <span class="nav-text">exec</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#与正则表达式相关的字符串方法"><span class="nav-number">5.</span> <span class="nav-text">与正则表达式相关的字符串方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#search"><span class="nav-number">5.1.</span> <span class="nav-text">search</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#match"><span class="nav-number">5.2.</span> <span class="nav-text">match</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#split"><span class="nav-number">5.3.</span> <span class="nav-text">split</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#replace"><span class="nav-number">5.4.</span> <span class="nav-text">replace</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zichong</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
